<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="/WEB-INF/html.tld" prefix="html" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>


<c:url var="rateCardsJsonObject" value="${util.en('/finance/ratecards/json')}" />
<c:url var="addRateard" value="${util.en('/finance/ratecard/add')}" />
<c:url var="delRateard" value="${util.en('/finance/ratecard/delete')}" />

<div id="rateCardView"></div>
			
<form:form id="financialProduct" modelAttribute ="financial" method="POST"  name="rateCard">
	<html:table attributes="class='inputTable' id='rateCardFormTable' style='display:none;'">
		  <html:tr>
		    <html:td><label><spring:message code="label.name" /></label></html:td>
		    
		    <html:td><label><spring:message code="label.min.amount" /></label></html:td>
		    <html:td><label><spring:message code="label.max.amount" /></label></html:td>
		    <html:td><label><spring:message code="label.description" /></label></html:td>
		  </html:tr>
		  <html:tr>
		    <html:td><form:input path="ratecard.name"></form:input></html:td>
		    <html:td><form:input path='ratecard.minAmount' class=" required amount"></form:input></html:td>
		    <html:td><form:input path='ratecard.maxAmount' class=" required amount"></form:input></html:td>
		    <html:td><form:input path="ratecard.description" class='required' size="45"></form:input></html:td>
		  </html:tr>
		 
		 
		  
	</html:table>
	 <form:hidden path="financial.financialProductId"  name="financial.financialProductId"/>
	 <form:hidden path="ratecard.rateCardId"  name="ratecard.rateCardId"/>
</form:form>


<div id="toolbar-options" style="float:right">
	<a id="addNewRate" >Add</a>
	<a id="editRate" >Edit</a>
	<a id="saveRate" >Save</a>
	<a id="deleteRate">Delete</a>
</div>	




<script>
$(function () {
	var dataToProcess;
	$( "#toolbar-options>a" ).button(); 
	$( ".button-holder #toolbar-options").remove();
	$( ".button-holder").append($( "#toolbar-options" ));
	  $(".date").datepicker();
	  $("select").chosen({width: "100%"});
	  
	  $("#addNewRate").click(function(){
		  console.log($("#rateCardFormTable").attr('display'));
		  $("#rateCardFormTable").show();
		  
	  });
	  $("#saveRate").click(function(){
		  console.log('clicked save rate card button');
		  submitForm('SAVE');
			return false;
		});
	  $("#deleteRate").click(function(){
		  console.log('clicked delete rate card button');
		  submitForm('DEL');
			return false;
		  
	  });
	  $("#editRate").click(function(){
		  $("#rateCardFormTable").show();
		$("#financialProduct input").each(function(){
			console.log("Field-"+this.id);
			var fieldId = this.id.substring();
			var tempId = fieldId.substring(fieldId.indexOf('.')+1,fieldId.length); 
			console.log("main maid id->"+tempId);
			$(this).val(dataToProcess[tempId]);
			
		});
		
			return false;
		  
	  });
	
var colM = [

{dataType: "string",dataIndx: "code", title: "Code",  width: 100},
{dataType: "string",dataIndx: "minAmount", title: "Lower Amount", width: 100},
{dataType: "string",dataIndx: "maxAmount", title: "Upper Amount", width: 100},
{dataType: "string",dataIndx: "description", title: "Description", width: 300}

	];
	  
	var dataModel = {
		        location: "remote",
		        sorting: "remote",
		      /*   paging: "remote", */ /* this will enable to show the pagination */
		        dataType: "JSON",
		        method: "GET",
		        curPage: 1,
		        getUrl: function () {
		            var sortDir = (this.sortDir == "up") ? "asc" : "desc";
		            var sort = ['userId', 'userName', 'firstName', 'lastName', 'languageCode', 'userStatus'];
		            return { url: "${rateCardsJsonObject}", data: "cur_page=" + this.curPage + "&records_per_page=" + 
		                this.rPP + "&sortBy=" + sort[this.sortIndx] + "&dir=" + sortDir+ "&financial.financialProductId=" + $("input[name='financial.financialProductId']").val() };
		        },
		        getData: function (dataJSON) {
		            
		            return { curPage: dataJSON.curPage, totalRecords: dataJSON.totalRecords, data: dataJSON };                
		        }
		    };
	    var grid1 = $("div#rateCardView").pqGrid({ width: "auto",
		        dataModel: dataModel,
		        colModel: colM,
		       /*  resizable: true,   */          
		        columnBorders: true,
		        flexHeight: true,
		        /*flexWidth: true, */
	            editable: false,
	            scrollModel: { horizontal: true }//,
	            /* topVisible:true,
	            hoverMode: 'cell' ,    
	            selectionModel: { type: 'cell' },    
	            editModel: { saveKey: '13' } */
		        
		    });
	    grid1.on("pqgridcellsave", function (evt, ui) {                       
	        
	        var data = ui.data, rowIndxPage = ui.rowIndxPage, dataIndx = ui.dataIndx, val = data[rowIndxPage][dataIndx];
	        //var orderID = data[rowIndxPage][2];
	        console.log(data[rowIndxPage]);
	        //var url = "../Demos/saveRecord?orderID=" + orderID+"&fieldname="+cols[dataIndx]+"&value="+val;
	        
	    });
	    grid1.on( "pqgridrowclick", function( event, obj ) {
	    	
	    	console.log(obj.dataModel.data[obj.rowIndx]);
	    	dataToProcess=obj.dataModel.data[obj.rowIndx];
	    	$("input[name='ratecard.rateCardId']").val(dataToProcess['rateCardId']);
	   
	  });
	 


function onSuccess(result)
    {
    	console.log(result);
    	 var DM = grid1.pqGrid("option", "dataModel");
         var data = DM.data;
         var temp=[];
         temp[0]=result.name;
         temp[1]=result.description;
         temp[2]=result.effectiveDate;
         temp[3]=result.expiryDate;
         console.log(temp);
         data.push(temp);
         console.log(data);
         grid1.pqGrid("refreshDataAndView");
         
         $("input[name='ratecard.rateCardId']").val(result.rateCardId);
       //TODO:ajax error rendering put it on common place
      	$( result.fieldError).each(function() {
     		console.log(this.field);
     		$('input[name="'+this.field+'"]').css( "border",'1px solid red' );
     	});
    }
    
   

function submitForm(action)
{
	 $('.amount').inputmask('remove');
		var formData;
		var url='#';
	if('SAVE'===action){
		formData = $("#financialProduct").serializeObject();
		url="${addRateard}";
		var params={url:url,success:onSuccess,data:formData,type:"POST",dataType:"json"};
		doAjax(params);
	}
	
	if('DEL'===action){
		formData = {};
		url="${delRateard}"+"/"+dataToProcess.rateCardId;
		var params={url:url,success:function(){grid1.pqGrid("refreshDataAndView");},data:formData,type:"POST",dataType:"json"};
		doAjax(params);
	}
	
}

});

function loadObject(objectId, ObjectType)
{
	$("input[name='ratecard.rateCardId']").val(objectId);
	console.log("rateCard Id = "+objectId);
	
}
</script>

